﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TestMutipleThreadRestEvent;

namespace fund
{ // 显示进度条的委托声明
    public delegate void ShowProgressDelegate(int totalStep, int currentStep);

    //test
    public partial class frmFund : Form
    {
        private List<Fund> table;
        private Random r = new Random();
        private CancellationTokenSource cts = new CancellationTokenSource();

        private DateTime startTime;

        public frmFund()
        {
            InitializeComponent();
        }

        private void frmFund_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 查询净值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            string FundDate = "";

            table = new List<Fund>();

            List<Fund> table1 = Task.Factory.StartNew(() => new Worker().GetFund(2, out FundDate, cts)).Result;
            List<Fund> table2 = Task.Factory.StartNew(() => new Worker().GetFund(3, out FundDate, cts)).Result;
            List<Fund> table3 = Task.Factory.StartNew(() => new Worker().GetFund(13, out FundDate, cts)).Result;
            List<Fund> table4 = Task.Factory.StartNew(() => new Worker().GetFund(5, out FundDate, cts)).Result;

            Task.WaitAll();

            table.AddRange(table1);
            table.AddRange(table2);
            foreach (Fund item in table3)
            {
                if (!table.Exists(p => p.FundCode == item.FundCode))
                    table.Add(item);
            }
            foreach (Fund item in table4)
            {
                if (!table.Exists(p => p.FundCode == item.FundCode))
                    table.Add(item);
            }

            table.RemoveAll(p => { return p.sgStatus == "场内交易" || p.sgStatus == "封闭期" || p.IsCanBuy == "未开通"; });

            //count:["1996","634","345","1017"],record:"2292",pages:"1",curpage:"1",indexsy:[0.76,0.74,-0.21,],showday:["2015-06-04","2015-06-03"]
            this.SafeCall(() =>
            {
                //foreach (DataRow r in table.Rows)
                //{
                //    dataGridView1.Rows.Add(r["Col14"], r["Col0"], r["Col1"], r["Col3"], r["Col4"], r["Col8"], r["Col9"], r["Col10"], r["Col12"], r["Col18"]);
                //}

                this.dataGridView1.AutoGenerateColumns = false;
                this.dataGridView1.DataSource = table;
                // lblInfo.Text = s1 + "\r\n" + s2 + "\r\n" + s3 + "%\r\n" + s4 + "\r\n" + "update:" + DateTime.Now.ToString("HH:mm:ss");
                this.label2.Text = FundDate;
                MessageBox.Show("1加载完成");
            });
        }

        //private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        //{
        //    for (int i = 0; i < e.RowCount; i++)
        //    {
        //        this.dataGridView1.Rows[e.RowIndex + i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

        //        this.dataGridView1.Rows[e.RowIndex + i].HeaderCell.Value = (e.RowIndex + i + 1).ToString();

        //        string code = this.dataGridView1.Rows[e.RowIndex + i].Cells["FundCode"].Value.ToString();

        //        //  Thread t = new Thread(new ParameterizedThreadStart(Do1));

        //        //t.Start(code + "," + (e.RowIndex + i));
        //    }
        //}

        //private void Do1(object cts)
        //{
        //    string[] datapass = (cts as string).Split(',');
        //    //while (!cts.IsCancellationRequested)
        //    //{
        //    string url = " http://fundsoft.eastmoney.com/fundapp2/symx.aspx?fc=" + (datapass[0]) + "&random=" + r.Next();
        //    string html = HtmlParseUtitly.GetHtmlSource(url, Encoding.UTF8);
        //    if (string.IsNullOrEmpty(html)) return;

        //    HtmlNode rootNode = null;
        //    HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
        //    document.LoadHtml(html);
        //    rootNode = document.DocumentNode;

        //    string s1 = HtmlParseUtitly.GetNodeText(rootNode, "//tbody/tr[1]/td[4]");//今年以来
        //    if (s1 == "---") s1 = "---|---";
        //    string s2 = HtmlParseUtitly.GetNodeText(rootNode, "//tbody/tr[2]/td[4]");//最近1周
        //    if (s2 == "---") s2 = "---|---";
        //    string s3 = HtmlParseUtitly.GetNodeText(rootNode, "//tbody/tr[3]/td[4]");//最近1月
        //    if (s3 == "---") s3 = "---|---";
        //    string s4 = HtmlParseUtitly.GetNodeText(rootNode, "//tbody/tr[4]/td[4]");//最近3月
        //    if (s4 == "---") s4 = "---|---";
        //    string s5 = HtmlParseUtitly.GetNodeText(rootNode, "//tbody/tr[5]/td[4]");//  最近6月
        //    if (s5 == "---") s5 = "---|---";
        //    string s6 = HtmlParseUtitly.GetNodeText(rootNode, "//tbody/tr[6]/td[4]");// 最近1年
        //    if (s6 == "---") s6 = "---|---";
        //    string s7 = HtmlParseUtitly.GetNodeText(rootNode, "//tbody/tr[7]/td[4]");//  最近2年
        //    if (s7 == "---") s7 = "---|---";
        //    string s8 = HtmlParseUtitly.GetNodeText(rootNode, "//tbody/tr[8]/td[4]");// 最近3年
        //    if (s8 == "---") s8 = "---|---";
        //    string s9 = HtmlParseUtitly.GetNodeText(rootNode, "//tbody/tr[9]/td[4]");//  最近5年
        //    if (s9 == "---") s9 = "---|---";
        //    string s10 = HtmlParseUtitly.GetNodeText(rootNode, "//tbody/tr[10]/td[4]");//  成立来

        //    this.SafeCall(() =>
        //    {
        //        for (int i = this.dataGridView1.Columns["ColRank"].Index;
        //             i < this.dataGridView1.Columns.Count; i++)
        //        {
        //            this.dataGridView1.Rows[int.Parse(datapass[1])].Cells[i].ValueType = typeof(int);
        //        }

        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank"].Value = ParseInt(s1.Split('|')[0]);
        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank1"].Value = ParseInt(s1.Split('|')[1]);

        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank3M"].Value = ParseInt(s4.Split('|')[0]);
        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank3M1"].Value = ParseInt(s4.Split('|')[1]);

        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank6M"].Value = ParseInt(s5.Split('|')[0]);
        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank6M1"].Value = ParseInt(s5.Split('|')[1]);

        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank1Y"].Value = ParseInt(s6.Split('|')[0]);
        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank1Y1"].Value = ParseInt(s6.Split('|')[1]);

        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank2Y"].Value = ParseInt(s7.Split('|')[0]);
        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank2Y1"].Value = ParseInt(s7.Split('|')[1]);

        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank3Y"].Value = ParseInt(s8.Split('|')[0]);
        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank3Y1"].Value = ParseInt(s8.Split('|')[1]);

        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank5Y"].Value = ParseInt(s9.Split('|')[0]);
        //        this.dataGridView1.Rows[int.Parse(datapass[1])].Cells["ColRank5Y1"].Value = ParseInt(s9.Split('|')[1]);

        //        // lblInfo.Text = s1 + "\r\n" + s2 + "\r\n" + s3 + "\r\n" + s4;
        //    });
        //    //    Thread.Sleep(1000 * 60); //每隔60s查询
        //    //}
        //}

        //private int ParseInt(string intValue)
        //{
        //    int aa = -1;
        //    if (!int.TryParse(intValue, out aa))
        //        aa = -1;
        //    return aa;
        //}

        /// <summary>
        /// 查询排名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            //    AutoResetEvent[] resets = new AutoResetEvent[table.Count];
            //    for (int i = 0; i < table.Count; i++)
            //    {
            //        resets[i] = new AutoResetEvent(false);
            //        worker w = new worker(table[i],resets[i]);
            //         ThreadPool.QueueUserWorkItem(new WaitCallback(w.work),null);
            //        //Thread thrd1 = new Thread(new ThreadStart(w.work));
            //        //thrd1.Start();
            //    }
            //    WaitHandle.WaitAll(resets);
            //    Console.WriteLine("ALL worker done - main exiting.");

            int numOfThread = table.Count;// ;
            startTime = DateTime.Now;
            // 显示进度条
            ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);

            //使用 MutipleThreadResetEvent
            using (var countdown = new MutipleThreadResetEvent(numOfThread))
            {
                for (int i = 0; i < numOfThread; i++)
                {
                    Worker w = new Worker(table[i], i, numOfThread, showProgress);
                    //开启N个线程，传递MutipleThreadResetEvent对象给子线程
                    ThreadPool.QueueUserWorkItem(new WaitCallback(w.workPM), countdown);
                }

                //dataGridView1.DataSource = table;
                //等待所有线程执行完毕
                //countdown.WaitAll();
            }

            //AutoResetEvent[] resets = new AutoResetEvent[table.Count];
            //for (int i = 0; i < table.Count; i++)
            //{
            //    resets[i] = new AutoResetEvent(false);
            //    worker w = new worker(table[i], resets[i]);
            //    ThreadPool.QueueUserWorkItem(new WaitCallback(w.work), null);
            //    //Thread thrd1 = new Thread(new ThreadStart(w.work));
            //    //thrd1.Start();
            //}
            //WaitHandle.WaitAll(resets);
            //Console.WriteLine("ALL worker done - main exiting.");

            //for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            //{
            //    string code = this.dataGridView1.Rows[i].Cells["FundCode"].Value.ToString();

            //    ThreadPool.QueueUserWorkItem(new WaitCallback(Do1), code + "," + (i));
            //}
        }

        /// <summary>
        /// 查询排名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            List<Fund> pmtable = Task.Factory.StartNew(() => new Worker().workPM()).Result;

            Task.WaitAll();

            this.dataGridView1.AutoGenerateColumns = false;

            if (table == null || table.Count == 0)
            {
                this.dataGridView1.DataSource = pmtable;
            }
            else
            {
                foreach (var item in pmtable)
                {
                    Fund fund = table.Find(p => p.FundCode == item.FundCode);
                    if (fund != null)
                    {
                        fund.ColGrow1W = item.ColGrow1W;
                        fund.ColGrow1M = item.ColGrow1M;
                        fund.ColGrow3M = item.ColGrow3M;
                        fund.ColGrow6M = item.ColGrow6M;
                        fund.ColGrow1Y = item.ColGrow1Y;
                        fund.ColGrow2Y = item.ColGrow2Y;
                        fund.ColGrow3Y = item.ColGrow3Y;
                        fund.ColGrow = item.ColGrow;
                        fund.ColGrowFrom6 = item.ColGrowFrom6;
                    }
                }
                this.dataGridView1.DataSource = table;
            }
            MessageBox.Show("1加载完成");
        }

        //查询历史净值
        private void button3_Click(object sender, EventArgs e)
        {
            int numOfThread = table.Count;// ;
            startTime = DateTime.Now;
            // 显示进度条
            ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);

            for (int i = 0; i < numOfThread; i++)
            {
                Worker w = new Worker(table[i], i, numOfThread, showProgress);
                ThreadPool.QueueUserWorkItem(new WaitCallback(w.workHistoryJZ), null);
            }
        }

        //查询基础信息
        private void button6_Click(object sender, EventArgs e)
        {
            int numOfThread = table.Count;// ;
            startTime = DateTime.Now;
            // 显示进度条
            ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);

            for (int currentNum = 0; currentNum < numOfThread; currentNum++)
            {
                Worker w = new Worker(table[currentNum], currentNum, numOfThread, showProgress);
                ThreadPool.QueueUserWorkItem(new WaitCallback(w.workJCXX), null);
            }
        }

        /// <summary>
        /// 获取最新估值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            List<Fund> gztable = Task.Factory.StartNew(() => new Worker().workGZ()).Result;

            Task.WaitAll();

            this.dataGridView1.AutoGenerateColumns = false;

            if (table == null || table.Count == 0)
            {
                this.dataGridView1.DataSource = gztable;
            }
            else
            {
                foreach (var item in gztable)
                {
                    Fund fund = table.Find(p => p.FundCode == item.FundCode);
                    if (fund != null) fund.gz = item.gz;
                }
                this.dataGridView1.DataSource = table;
            }
            MessageBox.Show("1加载完成");
        }

        /// <summary>
        /// 导出到EXCEL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            GPE.Utities.ExcelHelper.NPOIHelper.ExcelExporter.ExportToExcelByWinFromDataGridView(this.dataGridView1);
        }

        // 显示进度条
        private void ShowProgress(int totalStep, int currentStep)
        {
            if (_Progress.InvokeRequired)
            {
                ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);

                // 为了避免工作线程被阻塞，采用异步调用委托
                this.BeginInvoke(showProgress, new object[] { totalStep, currentStep });
            }
            else
            {
                _Progress.Maximum = totalStep;
                _Progress.Value = currentStep;
                if (totalStep == currentStep)
                {
                    MessageBox.Show("加载完成！" + (DateTime.Now - startTime).TotalSeconds);
                    ClearRows();
                    FormatGridRow();
                }
            }
        }

        private void ClearRows()
        {
            List<Fund> list = (List<Fund>)dataGridView1.DataSource;

            for (int i = 0; i < list.Count; i++)
            {
                Fund task = list[i] as Fund;
                if (task.IsCanBuy != "可以购买")
                {
                    // list.Remove(task);
                    task.Grade = "-";
                }
                //删除全部为3位数的
                if ((task.ColRank > 99 || task.ColRank < 0)
                    && (task.ColRank1W > 99)
                    && (task.ColRank1M > 99 || task.ColRank1M < 0)
                    && (task.ColRank3M > 99 || task.ColRank3M < 0)
                    && (task.ColRank6M > 99 || task.ColRank6M < 0)
                    && (task.ColRank1Y > 99 || task.ColRank1Y < 0)
                    )
                {
                    task.Grade = "-";
                    //  list.Remove(task);
                }
                if (!(
                     (task.ColRank6M < 0)
                      && (task.ColRank1Y < 0)
                      && (task.ColRank2Y < 0)
                      && (task.ColRank3Y < 0)
                      && (task.ColRank5Y < 0)
                      ))//不能同时为-1，成立半年以上
                {
                    if ((task.ColRank < 100 && task.ColRank > 0)
                        || (task.ColRank1W < 100 && task.ColRank1W > 0)
                        || (task.ColRank1M < 100 && task.ColRank1M > 0)
                        || (task.ColRank3M < 100 && task.ColRank3M > 0)
                        || (task.ColRank6M < 100 && task.ColRank6M > 0)
                        || (task.ColRank1Y < 100 && task.ColRank1Y > 0)
                        )
                    {//最近一年任意一个为2位数
                        task.Grade = "X";
                    }
                    if ((task.ColRank < 10 && task.ColRank > 0)
                        || (task.ColRank1W < 10 && task.ColRank1W > 0)
                        || (task.ColRank1M < 10 && task.ColRank1M > 0)
                        || (task.ColRank3M < 10 && task.ColRank3M > 0)
                        || (task.ColRank6M < 10 && task.ColRank6M > 0)
                        || (task.ColRank1Y < 10 && task.ColRank1Y > 0)
                        || (task.ColRank2Y < 10 && task.ColRank2Y > 0)
                        )
                    {//最近一年任意一个为1位数
                        task.Grade = "XX";
                    }
                    if ((task.ColRank < 100 || task.ColRank < 0)
                        && (task.ColRank3M < 100 || task.ColRank3M < 0)
                        && (task.ColRank6M < 100 || task.ColRank6M < 0)
                        && (task.ColRank1Y < 100 || task.ColRank1Y < 0)
                        && (task.ColRank2Y < 100 || task.ColRank2Y < 0)
                        && (task.ColRank3Y < 100 || task.ColRank3Y < 0)
                        )
                    {//最近3年全部为2位数
                        task.Grade = "XXX";
                    }
                    if ((task.ColRank < 20 || task.ColRank < 0)
                        && (task.ColRank3M < 20 || task.ColRank3M < 0)
                        && (task.ColRank6M < 20 || task.ColRank6M < 0)
                        && (task.ColRank1Y < 20 || task.ColRank1Y < 0)
                        && (task.ColRank2Y < 20 || task.ColRank2Y < 0)
                        && (task.ColRank3Y < 20 || task.ColRank3Y < 0)
                        )
                    {//最近3年全部为20位之内的
                        task.Grade = "XXXX";
                    }

                    if ((task.ColRank < 10 || task.ColRank < 0)
                        && (task.ColRank3M < 10 || task.ColRank3M < 0)
                        && (task.ColRank6M < 10 || task.ColRank6M < 0)
                        && (task.ColRank1Y < 10 || task.ColRank1Y < 0)
                        && (task.ColRank2Y < 10 || task.ColRank2Y < 0)
                        && (task.ColRank3Y < 10 || task.ColRank3Y < 0)
                        )
                    {//最近3年全部为1位之内的
                        task.Grade = "XXXXX";
                    }
                }
                else
                {
                    task.Grade = "新-";
                    if (!(
                     (task.ColRank1W < 0)
                      && (task.ColRank1M < 0)
                      && (task.ColRank3M < 0)
                      ))//不能同时为-1，成立半年以上
                    {
                        if ((task.ColRank1W < 100 && task.ColRank1W > 0)
                               || (task.ColRank1M < 100 && task.ColRank1M > 0)
                               || (task.ColRank3M < 100 && task.ColRank3M > 0)
                            )
                        {//最近三月内任意一个为2位数
                            task.Grade = "新X";
                        }
                        if ((task.ColRank1W < 100 || task.ColRank1W < 0)
                            && (task.ColRank1M < 100 || task.ColRank1M < 0)
                            && (task.ColRank3M < 100 || task.ColRank3M < 0)
                            )
                        {//最近一周全部为2位数
                            task.Grade = "新XX";
                        }
                        if ((task.ColRank1W < 20 || task.ColRank1W < 0)
                           && (task.ColRank1M < 20 || task.ColRank1M < 0)
                           && (task.ColRank3M < 20 || task.ColRank3M < 0)

                           )
                        {//最近一周全部为20位之内的
                            task.Grade = "新XXX";
                        }
                    }
                }
            }

            list.Sort((p1, p2) =>
            {
                var i = p2.Grade.CompareTo(p1.Grade);
                if (i == 0) i = p1.FundType.CompareTo(p2.FundType);
                if (i == 0) i = p1.ColRank1Y.CompareTo(p2.ColRank1Y);
                if (i == 0) i = p1.ColRank3M.CompareTo(p2.ColRank3M);
                return i;
            });
            IList list1 = (IList)list;

            dataGridView1.DataSource = null;

            dataGridView1.DataSource = list1;
        }

        /// <summary> 
        /// 格式化网格行  
        /// </summary> 
        private void FormatGridRow()
        {
            //循环遍历DataGridView的行集合  
            foreach (DataGridViewRow gridRow in this.dataGridView1.Rows)
            {
                //通过DataGridViewRow绑定的DataBoundItem对象得到Task  
                Fund task = gridRow.DataBoundItem as Fund;
                String stringValue = task.sgStatus;          //获取Task状态字符串  
                if (!string.IsNullOrEmpty(stringValue))
                {
                    if (stringValue == "暂停申购")//如果当前任务的状态标记为已完成  
                    {
                        //设置DataGridViewRow行的默认样式  
                        gridRow.DefaultCellStyle.Font = new Font("Arial", 9, FontStyle.Strikeout);
                        //指定行的前景色为亮灰色  
                        gridRow.DefaultCellStyle.ForeColor = Color.LightGray;
                    }
                }
                if (!((task.ColRank < 0)
                    && (task.ColRank1Y < 0)
                    && (task.ColRank2Y < 0)
                    && (task.ColRank3M < 0)
                    && (task.ColRank3Y < 0)
                    && (task.ColRank5Y < 0)
                    && (task.ColRank6M < 0)))//不能同时为-1
                {
                    if ((task.ColRank < 99 || task.ColRank < 0)
                        && (task.ColRank1Y < 99 || task.ColRank1Y < 0)
                        && (task.ColRank2Y < 99 || task.ColRank2Y < 0)
                        && (task.ColRank3M < 99 || task.ColRank3M < 0)
                        && (task.ColRank3Y < 99 || task.ColRank3Y < 0)
                        && (task.ColRank5Y < 99 || task.ColRank5Y < 0)
                        && (task.ColRank6M < 99 || task.ColRank6M < 0))
                    {//全部为2位数
                        using (Font font = new Font("Arial", 9, FontStyle.Regular))
                        {
                            gridRow.DefaultCellStyle.Font = font;
                        }

                        //指定行的前景色为亮灰色  
                        gridRow.DefaultCellStyle.ForeColor = Color.Red;
                    }
                    if ((task.ColRank < 20 || task.ColRank < 0)
                          && (task.ColRank1Y < 20 || task.ColRank1Y < 0)
                          && (task.ColRank2Y < 20 || task.ColRank2Y < 0)
                          && (task.ColRank3M < 20 || task.ColRank3M < 0)
                          && (task.ColRank3Y < 20 || task.ColRank3Y < 0)
                          && (task.ColRank5Y < 20 || task.ColRank5Y < 0)
                          && (task.ColRank6M < 20 || task.ColRank6M < 0))
                    {
                        using (Font font = new Font("Arial", 9, FontStyle.Bold))
                        {
                            gridRow.DefaultCellStyle.Font = font;
                        }

                        //指定行的前景色为亮灰色  
                        gridRow.DefaultCellStyle.ForeColor = Color.Red;
                    }

                    if ((task.ColRank < 10 || task.ColRank < 0)
                        && (task.ColRank1Y < 10 || task.ColRank1Y < 0)
                        && (task.ColRank2Y < 10 || task.ColRank2Y < 0)
                        && (task.ColRank3M < 10 || task.ColRank3M < 0)
                        && (task.ColRank3Y < 10 || task.ColRank3Y < 0)
                        && (task.ColRank5Y < 10 || task.ColRank5Y < 0)
                        && (task.ColRank6M < 10 || task.ColRank6M < 0))
                    {
                        using (Font font = new Font("Arial", 9, FontStyle.Bold))
                        {
                            gridRow.DefaultCellStyle.Font = font;
                        }

                        //指定行的前景色为亮灰色  
                        gridRow.DefaultCellStyle.ForeColor = Color.Red;
                    }
                }
            }
        }

        /// <summary>
        /// 单元格格式化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;

            object originalValue = e.Value;

            if (dgv.Columns[e.ColumnIndex].DataPropertyName == "操作类型")
            {
                e.Value = ((int)originalValue == 1) ? "缴费" : "退费";
            }

            if (e.RowIndex < dgv.Rows.Count - 1)//这个判断,如果DataGridView没有设置为添加.就可以不要了
            {
                if (e.ColumnIndex == dgv.Columns["Apply_Date"].Index)
                {
                    if (e.Value == null)
                    {
                        return;
                    }
                    if (e.Value.Equals("0"))
                    {
                        e.Value = "否";
                        //e.CellStyle.ForeColor = Color.Green;
                    }
                    else
                    {
                        e.Value = Convert.ToDateTime(e.Value).ToString("yyyy-M-d");
                    }
                }
            }
        }

        private void dataGridView1_RowPostPaint_1(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rowHeaderBounds = new Rectangle
            (
                 2, e.RowBounds.Top,
                 this.dataGridView1.RowHeadersWidth - 2, e.RowBounds.Height - 1
            );

            using (Brush backbrush =
                new SolidBrush(SystemColors.Control))
            {
                e.Graphics.FillRectangle(backbrush, rowHeaderBounds);
            }

            if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
            {
                using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
                {
                    int linen = 0;
                    linen = e.RowIndex + 1;
                    string line = linen.ToString();
                    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
                    SolidBrush B = new SolidBrush(Color.Red);
                }
            }
        }
    }
}